#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_vdVideoDecode.globalInit();
    m_playImage = this->findChild<FrameOpenGLWidget *>("widget");
    connect(this, SIGNAL(sgnUpdateFrameFormat(int)), this, SLOT(sltUpdateFrameFormat(int)), Qt::BlockingQueuedConnection);
}

MainWindow::~MainWindow()
{
    delete ui;
    m_vdVideoDecode.globalUnInit();
}

void  MainWindow::sltUpdateFrameFormat(int nFormatType)
{
    if(m_vdVideoDecode.isClose())
        return;

    m_playImage->setFrameDataFormat((FrameDataFormat)nFormatType);
}

void MainWindow::on_pushButtonOpenFile_clicked(bool checked)
{
    bool bIsSupportHardware = ui->checkBoxHW->checkState() == Qt::Checked ? true:false;
    QString filename = QFileDialog::getOpenFileName(nullptr, "Open Video File");
   if (!filename.isEmpty())
    {
       m_vdVideoDecode.setHWDecoder(bIsSupportHardware);
       m_vdVideoDecode.setStreamDecodeCallback([](int nStreamType, int nFormatType, long long llDecodeTs, long long llPlayTs, int width, int height, unsigned char ** pStreamData, int * linesize, void * pUserData){
           MainWindow *pMainWindow = (MainWindow *)pUserData;

          if(nFormatType !=  pMainWindow->m_playImage->getFrameDataFormat())
          {
              //发送信号出去，更新opengl初始化纹理。（因为opengl初始化纹理是非线程安全的，需要在UI或同FrameOpenGLWidget线程中处理。）
              emit pMainWindow->sgnUpdateFrameFormat(nFormatType);
          }

          pMainWindow->m_playImage->updateFrame(nFormatType, pStreamData, linesize, width, height);
       },this);
       m_vdVideoDecode.setFileStatusCallback([](int FileStatus, int nErrorCode, void * pUserData){
            qDebug()<<"file is end";
       },this);

       m_vdVideoDecode.open(filename);
    }
}

void MainWindow::on_pushButtonCloseFile_clicked()
{
    m_vdVideoDecode.close();
}
